﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Controls;
using SLS.DataBase;
using SLS.ExClassLib.DataType;
using SLS.ExClassLib.Database;
using SLS.ExClassLib.Message;
using SLS.ExClassLib.Events;
using SLS.ExClassLib.WCFClient;
using SLS.ExClassLib.Data;
namespace SLS.Base
{
    public partial class SLBC 
    {
        public virtual void LoadCreatedRecord(DataSet set2Create, string InstanceID, MessageEx msg)
        { 

        }
        public virtual void SetUpSet5Property(DataSet set5Property, string InstanceID)
        { } 
        public virtual void CMDEXE_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            { 
                ExDataRow dwThis = (ExDataRow)e.Source;
                TextBox cmd = sender as TextBox;
                string cmdtext = cmd.Text;
                switch (cmdtext)
                {
                    case "I":
                        commandInformation(dwThis);
                        break;
                    case "N":
                        break;
                    case "M":
                        commandModify(dwThis);
                        break;
                    case "C":
                        commandCopy(dwThis);
                        break;
                    case "D":
                        commandDelete(dwThis);
                        break;
                    case "S": 
                        break;
                    default:
                        break;
                } 
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        public virtual ExDataRow commandNew(string SM, string KEYDEFTYPE, string GTPRE, string GTKEY, string KEYINSTANCETABLE)
        {
            ExDataRow row = null;
            try
            {
                row = ExRowBase.OnNewRecord(SM, KEYDEFTYPE, GTPRE, GTKEY, KEYINSTANCETABLE);
            }
            catch (Exception ex)
            {
                throw;
            }
            return row;
        }
        public virtual ExDataRow commandCopy(ExDataRow dwThis)
        {
            ExDataRow row = null;
            try
            {
                DataRow dwNewRecord = dwThis.GetCopyRow(dwThis);
                dwThis.OnCreateByQueryFinish(dwNewRecord, dwThis.Item);
            }
            catch (Exception ex)
            {
                throw;
            }
            return row;
        }
        public virtual void commandDelete(ExDataRow dwThis)
        {
            try
            {
               
                dwThis.OnDeleteRecord(dwThis);

            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public virtual void commandModify(ExDataRow dwThis)
        {
            try
            {
                DataRow dwNew = TableBase.NewRow();
                dwNew["INSTANCEID"] = Guid.NewGuid().ToString().ToUpper();

                DataSet setEvent = new DataSet();
                setEvent.Tables[dwNew.Table.TableName].Rows.Add(dwNew);

            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public virtual void commandInformation(ExDataRow dwThis)
        {
            try
            {
                DataRow dwNew = TableBase.NewRow();
                dwNew["INSTANCEID"] = Guid.NewGuid().ToString().ToUpper(); 
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public virtual void commandSave(ExDataRow dwThis)
        {
            try
            {
                 dwThis.OnSaveRecord(1); 
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public virtual DataSet MergeUI_Model_Data(DataRow dwReference, DataRow dwModel, List<string> ForeignKeyList, List<string> PrimaryKeyList, DataSet set4Reference)
        {
            DataRow dwTarget = null;
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            string TBName = dwReference.Table.TableName;
            try
            {
                //1st, 保留参考数据传递过来的信息，一般是主键信息。只要字段名相同就复制。
                //dwTarget = DataAccessService.Instance.MapDataRow("", "", TBName, dwReference, null, null, false);
                if (TBName.Contains("QueryCond"))
                {
                    dwTarget =ViewDataSet.SetQuery.Tables[TBName].NewRow();
                }
                else
                {
                    dwTarget = ViewDataSet.SetGlobal.Tables[TBName].NewRow();
                }
                DataAccessService.Instance.MapDataRow(ref dwTarget, dwReference, false);
                dwTarget["SM"] = dwReference["SM"];
                dwTarget["INSTANCEID"] = Guid.NewGuid().ToString().ToUpper();
                //2.根据指定的字段，将主键字段进一步扩展填充。有些字段名不同，但是也要借助这个个规则，进行复制数据。
                DataAccessService.Instance.MapDataRow(ref dwTarget, dwReference, ForeignKeyList, PrimaryKeyList, true);
                //3.根据相同列表，将模板数据进行映射。
                DataAccessService.Instance.MapDataRow(ref dwTarget, dwModel, ForeignKeyList, PrimaryKeyList, true);
                DataAccessService.Instance.ImportDataTable(ref setReturn, dwTarget);
            }
            catch (Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        
        #region =================SLBC VALIDATE=========
        public virtual void SetUpKeyRelation(DataRow dwSource)
        {
        }
        public virtual void cmbForeignKey_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        #endregion

        #region=================WORKFLOW VALIDATE============

        public void UpdateByForeignKeyWithReason(DataSet setSource, SLDBSET setEnv, DataRow dwTarget, string Reason)
        {
            try
            {
                #region Prepare Condition
                DataRow dwForeignKeyList = null;
                string TBName = dwTarget.Table.TableName;
                string expression = "TableName='" + TBName + "'";
                DataRow[] dwForeignKeyLists = setEnv.Tables["ForeignKeyList"].Select(expression);
                if (dwForeignKeyLists.Count() == 0)
                {
                    setEnv = (SLDBSET)DataAccessService.Instance.LoadForeignKeyList(TBName, setEnv);
                }
                expression = "TableName='" + TBName + "' and ForeignKey='" + Reason + "'";
                dwForeignKeyLists = setEnv.Tables["ForeignKeyList"].Select(expression);
                if (dwForeignKeyLists.Count() > 0)
                {
                    dwForeignKeyList = dwForeignKeyLists[0];
                }
                else
                {
                    Tracer.Warn("UpdateByForeignKey(MessageEx This_Message) ", "dwForeignKeyList is Null");
                    return;
                }
                string FUpdateType = dwForeignKeyList["UpdateType"].ToString().Trim();
                string FPrimaryKeyTable = dwForeignKeyList["TargetTable"].ToString().Trim();

                string DtQueryCond = FPrimaryKeyTable;

                Queue TargetKeyList = new Queue();
                Queue SourceKeyList = new Queue();
               
                dicSource =ExRowBase .BuildKeyPair(dicSource, dwForeignKeyList, dwTarget);
                SourceKeyList = (Queue)dicSource["SourceKeyList"];
                TargetKeyList = (Queue)dicSource["TargetKeyList"];
                DtQueryCond = (string)dicSource["DtQueryCond"];
                #endregion

                #region FUpdateType == "IsNull"
                if (FUpdateType == "IsNull")
                {
                    DataRow dwSource = setSource.Tables[DtQueryCond].Rows[0];
                    dwTarget = DataAccessService.Instance.MapDataRow("", "", TBName, dwTarget, dwSource, TargetKeyList, SourceKeyList);
                }
                #endregion

                #region FUpdateType == "IsComplete"
                if (FUpdateType == "IsComplete")
                {
                    DataTable dtDataSetConclusion = setSource.Tables["DataSetConclusion"];
                    expression = "TableName='" + DtQueryCond + "'";
                    DataRow[] query = setEnv.Tables["DataSetConclusion"].Select(expression);
                    /*
                    query = from dwConclusion in dtDataSetConclusion.AsEnumerable()
                            where dwConclusion["TableName"].ToString().TrimEnd() == DtQueryCond
                            select dwConclusion;*/
                    string Conclusion = "";
                    if (query.Count() > 0)
                    {
                        foreach (DataRow dwTemp in query)
                        {
                            Conclusion = dwTemp["Conclusion"].ToString().Trim();
                        }
                    }
                    if (Conclusion == "TOTALCOMPLETE")
                    {
                        dwTarget["SUBSTATUS"] += DtQueryCond + "Complete";
                        /*foreach (DataTable tbTemp in setSource.Tables)
                        {
                            if (tbTemp.TableName != BaseTable)
                            {
                                setUI = (SLDBSET)DataAccessService.Instance.ImportDataTable(setUI, tbTemp);
                            }
                        }*/
                    }
                }
                #endregion
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
        public void UpdateByForeignKey(MessageEx This_Message)
        {
            try
            {
                Fluent.MenuItem sender = new Fluent.MenuItem();
                DataSet setSource = This_Message.setEvent;
                string Reason = GetReason(This_Message);
                DataRow m_ActiveDataRow = null;
                UpdateByForeignKeyWithReason(setSource, SetUI, m_ActiveDataRow, Reason);
                sender.Name = "OnUpdateDone";
                ActivateMenuItem(sender, null);
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
       
        private string GetReason(MessageEx This_Message)
        {
            string Reason = "";
            try
            {
                foreach (DataTable tbTemp in This_Message.setEvent.Tables)
                {
                    if (!tbTemp.TableName.Contains("QueryCond"))
                        continue;
                    else
                    {
                        if (tbTemp.Rows.Count > 0)
                        {
                            Reason = tbTemp.Rows[0]["REASON1"].ToString().Trim();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return Reason;
        }
        private int FindRowIndex(DataGridRow row)
        {
            DataGrid dataGrid = ItemsControl.ItemsControlFromItemContainer(row) as DataGrid;

            int index = dataGrid.ItemContainerGenerator.IndexFromContainer(row);

            return index;
        }
        #endregion
    }
}